/*
 * @Author: gy
 * @Date: 2019-06-15 08:58:25
 * @LastEditors  : gy
 * @LastEditTime : 2020-01-21 18:10:50
 */
let res = ''

function recursive(menu, txt) {
  for (let i = 0; i < menu.length; i++) {
    if (menu[i]['context'] && menu[i]['context'] != txt) {
      if (menu[i]['childs'] && menu[i]['childs'].length > 0) {
        recursive(menu[i]['childs'], txt)
      }
    } else {
      res = menu[i]
      break
    }
  }
  return res
}
const commTool = {
  install(Vue) {
    Vue.prototype.$getType = obj => {
      return (obj == null
        ? String(obj)
        : Object.prototype.toString.call(obj).replace(/\[object\s+(\w+)\]/i, '$1') || 'Object'
      ).toLowerCase()
    }
    Vue.prototype.$getObjLen = obj => {
      return Object.keys(obj).length
    }
    Vue.prototype.$replaceField = (dataSource, column) => {
      let res = []
      for (let i in dataSource) {
        let isHas = column.filter(item => {
          return item.key == i
        })
        if (isHas.length > 0) {
          res.push({
            key: isHas[0]['key'],
            title: isHas[0]['title'],
            value: dataSource[i]
          })
        }
      }
      return res
    }
    Vue.prototype.$hashString = () => {
      let str = ''
      let random = (() => {
        for (let i = 0; i < 4; i++) {
          str += Math.round(Math.random() * 1000)
        }
        return str
      })()
      return random
    }
    Vue.prototype.$throttle = (fn, int) => {
      let timeInt = null
      let context = this
      return event => {
        clearTimeout(timeInt)
        timeInt = setTimeout(() => {
          fn.call(context, event)
        }, int || 500)
      }
    }
    Vue.prototype.$loadScript = (url, callFn, errFn) => {
      if (!url) return '文件地址不能为空'
      let head = document.getElementsByTagName('head')[0]
      let script = document.createElement('script')
      script.type = 'text/javascript'
      script.charset = 'UTF-8'
      script.src = url
      head.appendChild(script)
      let loadTimeout = setTimeout(errFn, 2000)
      script.onload = () => {
        clearTimeout(loadTimeout)
        callFn.call()
      }
    }
    Vue.prototype.$getNowFormatTime = sperator => {
      let sep = sperator || '-'
      let date = new Date()
      let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      let strDate = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      let currentdate =
        date.getFullYear() +
        sep +
        month +
        sep +
        strDate +
        ' ' +
        date.getHours() +
        ':' +
        date.getMinutes() +
        ':' +
        date.getSeconds()
      return currentdate
    }
    /**
     * @description: 调用lodop打印
     * @return:{promise}
     */
    Vue.prototype.$getLodop = () => {
      return new Promise((resolve, reject) => {
        if (!window.LODOP_SERVER_URL || !window.LODOP) {
          Vue.prototype.$loadScript(
            './CLodopfuncs.js',
            () => {
              window.LODOP_SERVER_URL = 'http://localhost:8000'
              let initStatus = window.LODOP.PRINT_INIT()
              if (!initStatus) {
                this.$error({
                  title: '打印初始化失败',
                  content: '前一个打印事务未完成或未找到可用打印机'
                })

                reject('打印初始化失败,前一个打印事务未完成或未找到可用打印机')
              }
              resolve(window.LODOP)
            },
            () => {
              this.$error({
                title: '配置错误',
                content: '加载打印文件失败，未启动LODOP或IP地址配置错误，请检查后重试'
              })
              reject('加载打印文件失败，未启动LODOP或IP地址配置错误，请检查后重试')
            }
          )
        } else {
          resolve(window.LODOP)
        }
      })
    }
    /**
     * @description: 右键点击出现菜单
     * @param {evt} 事件对象
     * @param {menu} 菜单对象 [{context:'菜单1',index:0}]
     * @param {callback} 选中菜单项后回调函数
     */
    Vue.prototype.$contextmenu = (evt, menu, callback) => {
      evt.preventDefault()
      if (document.getElementsByClassName('contextmenu').length > 0) {
        document.getElementsByTagName('body')[0].removeChild(document.getElementsByClassName('contextmenu')[0])
      }
      let x = evt.clientX
      let y = evt.clientY
      let ele = document.createElement('ul')
      ele.className = 'contextmenu'
      ele.style.left = `${x}px`
      ele.style.top = `${y}px`
      let str = ''
      menu.map(item => {
        if (item.childs && item.childs.length > 0) {
          str += `<li class="has-child">${item.context}`
          str += '<ul class="child">'
          item.childs.map(child => {
            str += `<li>${child.context}</li>`
          })
          str += '</ul>'
        } else {
          str += `<li>${item.context}`
        }
        str += '</li>'
      })
      ele.innerHTML = str
      document.getElementsByTagName('body')[0].appendChild(ele)

      document.querySelectorAll('.contextmenu')[0].onclick = function() {
        let txt = event.target.innerHTML
        if (!txt) return console.log('未获取到文本内容')
        let res = recursive(menu, txt)
        callback(res)
        if (document.getElementsByClassName('contextmenu').length > 0) {
          document.getElementsByTagName('body')[0].removeChild(document.getElementsByClassName('contextmenu')[0])
        }
      }
    }

    /**
     * @description: 监听鼠标滚轮事件
     * @param {callFn} 处理事件
     * @param {flag} 销毁标志
     * @return:
     */

    Vue.prototype.$mousewheel = (callFn, flag) => {
      if (flag) {
        if (document.addEventListener) {
          document.addEventListener('DOMMouseScroll', callFn, false)
        }
        window.onmousewheel = document.onmousewheel = callFn
      } else {
        document.removeEventListener('mousewheel', callFn)
        window.onmousewheel = document.onmousewheel = null
      }
    }
  }
}

export default commTool
